<template>
    <div class="detail-container">
        <!-- 头部信息 -->
        <div class="detail-header">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>病虫害详情</el-breadcrumb-item>
                <el-breadcrumb-item>{{ pestDiseaseData.name || '加载中...' }}</el-breadcrumb-item>
            </el-breadcrumb>

            <div class="header-content">
                <div class="title-section">
                    <h1>{{ pestDiseaseData.name || '病虫害详情' }}</h1>
                    <el-tag v-if="pestDiseaseData.type" :type="getTagType(pestDiseaseData.type)" size="large">
                        {{ pestDiseaseData.type }}
                    </el-tag>
                </div>
            </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
            <el-skeleton :rows="8" animated />
        </div>

        <!-- 详情内容 - 两列布局 -->
        <div v-else-if="pestDiseaseData.id" class="detail-content">
            <div class="equal-height-container">
                <!-- 左侧列 - 基本信息 -->
                <div class="left-column">
                    <!-- 基本信息卡片 -->
                    <el-card class="info-card" shadow="hover">
                        <template #header>
                            <div class="card-header">
                                <el-icon class="card-icon">
                                    <InfoFilled />
                                </el-icon>
                                <span>基本信息</span>
                            </div>
                        </template>

                        <el-descriptions :column="1" border>
                            <el-descriptions-item label="病虫害名称">
                                {{ pestDiseaseData.name }}
                            </el-descriptions-item>
                            <el-descriptions-item label="类型">
                                <el-tag :type="getTagType(pestDiseaseData.type)">
                                    {{ pestDiseaseData.type }}
                                </el-tag>
                            </el-descriptions-item>
                            <el-descriptions-item label="作物种类ID">
                                {{ pestDiseaseData.categoryId }}
                            </el-descriptions-item>
                            <el-descriptions-item label="创建时间">
                                {{ formatDate(pestDiseaseData.createTime) }}
                            </el-descriptions-item>
                            <el-descriptions-item label="更新时间">
                                {{ formatDate(pestDiseaseData.updateTime) }}
                            </el-descriptions-item>
                        </el-descriptions>
                    </el-card>

                    <!-- 症状描述 -->
                    <el-card class="info-card" shadow="hover" v-if="pestDiseaseData.symptoms">
                        <template #header>
                            <div class="card-header">
                                <el-icon class="card-icon symptoms-icon">
                                    <View />
                                </el-icon>
                                <span>症状描述</span>
                            </div>
                        </template>
                        <div class="content-text">
                            {{ pestDiseaseData.symptoms }}
                        </div>
                    </el-card>

                    <!-- 发生条件 -->
                    <el-card class="info-card" shadow="hover" v-if="pestDiseaseData.occurrenceCondition">
                        <template #header>
                            <div class="card-header">
                                <el-icon class="card-icon conditions-icon">
                                    <Sunny />
                                </el-icon>
                                <span>发生条件</span>
                            </div>
                        </template>
                        <div class="content-text">
                            {{ pestDiseaseData.occurrenceCondition }}
                        </div>
                    </el-card>

                    <!-- 防治方法 -->
                    <el-card class="info-card" shadow="hover" v-if="pestDiseaseData.controlMethods">
                        <template #header>
                            <div class="card-header">
                                <el-icon class="card-icon methods-icon">
                                    <Setting />
                                </el-icon>
                                <span>防治方法</span>
                            </div>
                        </template>
                        <div class="content-text">
                            {{ pestDiseaseData.controlMethods }}
                        </div>
                    </el-card>
                </div>

                <!-- 右侧列 - 图片和知识图谱 -->
                <div class="right-column">
                    <!-- 症状图片 -->
                    <div class="right-section image-section">
                        <el-card class="full-height-card" shadow="hover">
                            <template #header>
                                <div class="card-header">
                                    <el-icon class="card-icon">
                                        <Picture />
                                    </el-icon>
                                    <span>症状图片</span>
                                </div>
                            </template>
                            <div class="card-content">
                                <div v-if="imageList.length > 0" class="image-gallery">
                                    <!-- 单张图片时占满整个容器 -->
                                    <div v-if="imageList.length === 1" class="single-image-container">
                                        <el-image :src="imageList[0]" :alt="`${pestDiseaseData.name}症状图片`" fit="contain"
                                            :preview-src-list="imageList" :initial-index="0" class="single-image">
                                            <template #error>
                                                <div class="image-error-large">
                                                    <el-icon size="48">
                                                        <Picture />
                                                    </el-icon>
                                                    <span>图片加载失败</span>
                                                </div>
                                            </template>
                                        </el-image>
                                    </div>

                                    <!-- 多张图片时主图+缩略图布局 -->
                                    <div v-else class="multiple-images-container">
                                        <!-- 主图 -->
                                        <div class="main-image-container">
                                            <el-image :src="imageList[currentImageIndex]"
                                                :alt="`${pestDiseaseData.name}症状图片${currentImageIndex + 1}`" fit="contain"
                                                :preview-src-list="imageList" :initial-index="currentImageIndex"
                                                class="main-image">
                                                <template #error>
                                                    <div class="image-error-large">
                                                        <el-icon size="32">
                                                            <Picture />
                                                        </el-icon>
                                                        <span>图片加载失败</span>
                                                    </div>
                                                </template>
                                            </el-image>
                                        </div>

                                        <!-- 缩略图列表 -->
                                        <div class="thumbnail-container">
                                            <div v-for="(image, index) in imageList" :key="index" class="thumbnail-item"
                                                :class="{ active: index === currentImageIndex }"
                                                @click="switchMainImage(index)">
                                                <el-image :src="image" :alt="`${pestDiseaseData.name}症状图片${index + 1}`"
                                                    fit="cover" class="thumbnail-image">
                                                    <template #error>
                                                        <div class="thumbnail-error">
                                                            <el-icon size="16">
                                                                <Picture />
                                                            </el-icon>
                                                        </div>
                                                    </template>
                                                </el-image>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div v-else class="no-content">
                                    <el-empty description="暂无症状图片" :image-size="80" />
                                </div>
                            </div>
                        </el-card>
                    </div>

                    <!-- 🔥 知识图谱 - 实现真实功能 -->
                    <div class="right-section graph-section">
                        <el-card class="full-height-card" shadow="hover">
                            <template #header>
                                <div class="card-header">
                                    <el-icon class="card-icon graph-icon">
                                        <DataBoard />
                                    </el-icon>
                                    <span>知识图谱</span>
                                    <el-button 
                                        v-if="!knowledgeGraphLoading && knowledgeGraphData.nodes && knowledgeGraphData.nodes.length > 0"
                                        type="text" 
                                        size="small"
                                        @click="goToFullGraph"
                                        style="margin-left: auto;">
                                        查看完整图谱
                                    </el-button>
                                </div>
                            </template>
                            <div class="card-content">
                                <div class="knowledge-graph-container" v-loading="knowledgeGraphLoading">
                                    <!-- 🔥 实际的知识图谱展示区域 -->
                                    <div 
                                        v-if="!knowledgeGraphLoading && knowledgeGraphData.nodes && knowledgeGraphData.nodes.length > 0"
                                        id="detail-knowledge-graph" 
                                        ref="detailGraphContainer"
                                        class="detail-graph-display">
                                    </div>
                                    
                                    <!-- 🔥 加载状态 -->
                                    <div v-else-if="knowledgeGraphLoading" class="graph-loading">
                                        <el-icon class="is-loading" size="32"><Loading /></el-icon>
                                        <p>正在生成知识图谱...</p>
                                    </div>
                                    
                                    <!-- 🔥 无数据状态 -->
                                    <div v-else class="knowledge-graph-placeholder">
                                        <el-empty description="知识图谱数据加载失败" :image-size="100">
                                            <template #description>
                                                <p style="color: #909399; margin-top: 10px;">
                                                    无法加载相关知识图谱<br />
                                                    <el-button type="primary" size="small" @click="retryLoadGraph">
                                                        重新加载
                                                    </el-button>
                                                    <el-button type="info" size="small" @click="createTestGraphData" style="margin-left: 8px;">
                                                        测试数据
                                                    </el-button>
                                                </p>
                                            </template>
                                        </el-empty>
                                    </div>
                                </div>
                            </div>
                        </el-card>
                    </div>
                </div>
            </div>
        </div>

        <!-- 数据为空状态 -->
        <el-empty v-else-if="!loading" description="未找到相关病虫害信息" :image-size="200">
            <el-button type="primary" @click="goBack">返回列表</el-button>
        </el-empty>

        <!-- 操作按钮区域 -->
        <div class="action-bar" v-if="!loading && pestDiseaseData.id">
            <el-button @click="goBack">
                <el-icon>
                    <ArrowLeft />
                </el-icon>
                返回列表
            </el-button>
            <el-button type="primary" @click="printDetail">
                <el-icon>
                    <Printer />
                </el-icon>
                打印详情
            </el-button>
            <el-button type="success" @click="exportDetail">
                <el-icon>
                    <Download />
                </el-icon>
                导出详情
            </el-button>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
    ArrowLeft,
    InfoFilled,
    View,
    Sunny,
    Setting,
    Picture,
    Printer,
    Download,
    DataBoard,
    Loading
} from '@element-plus/icons-vue'
import * as d3 from 'd3'

// 🔥 导入API
import { getPestDiseaseByName } from '@/api/agriculture/guo/pestdisease/detail'
import { getKnowledgeGraphDataWithSpecificNode } from '@/api/agriculture/guo/knowledge/knowledgeGraph'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(true)
const pestDiseaseData = ref({})
const currentImageIndex = ref(0) // 当前显示的主图索引

// 🔥 知识图谱相关数据
const knowledgeGraphLoading = ref(false)
const knowledgeGraphData = ref({ nodes: [], links: [] })
const detailGraphContainer = ref(null)
let detailSvg = null

// 🔥 获取标签类型的方法
const getTagType = (type) => {
    switch (type) {
        case '病害':
            return 'danger'
        case '虫害':
            return 'warning'
        case '生理性病害':
            return 'info'
        default:
            return 'info'
    }
}

// 计算属性 - 处理图片URL列表
const imageList = computed(() => {
    if (!pestDiseaseData.value.imageUrls) return []

    // 如果是字符串，按逗号分割
    if (typeof pestDiseaseData.value.imageUrls === 'string') {
        return pestDiseaseData.value.imageUrls
            .split(',')
            .map(url => url.trim())
            .filter(url => url)
    }

    // 如果已经是数组，直接返回
    return Array.isArray(pestDiseaseData.value.imageUrls)
        ? pestDiseaseData.value.imageUrls
        : []
})

// 🔥 加载知识图谱数据
const loadKnowledgeGraph = async () => {
    if (!pestDiseaseData.value.name) {
        console.log('病虫害名称为空，无法加载知识图谱')
        return
    }
    
    try {
        knowledgeGraphLoading.value = true
        console.log('🔍 开始加载知识图谱:', pestDiseaseData.value.name)
        
        const response = await getKnowledgeGraphDataWithSpecificNode({
            centerNode: 'crop_1', // 默认小麦，API会自动判断
            specificNodeName: pestDiseaseData.value.name,
            nodeType: pestDiseaseData.value.type
        })
        
        console.log('📊 知识图谱响应:', response)
        
        if (response.code === 200 && response.data) {
            knowledgeGraphData.value = {
                nodes: response.data.nodes || [],
                links: response.data.links || []
            }
            
            console.log('✅ 知识图谱数据加载成功:', knowledgeGraphData.value)
            
            // 🔥 修复：等待DOM完全更新后再渲染图谱
            knowledgeGraphLoading.value = false
            
            // 使用setTimeout确保DOM完全渲染
            setTimeout(() => {
                renderDetailGraph()
            }, 100)
            
        } else {
            console.error('❌ 知识图谱加载失败:', response.msg)
            ElMessage.warning('知识图谱加载失败')
        }
    } catch (error) {
        console.error('💥 知识图谱加载出错:', error)
        ElMessage.error('知识图谱加载失败')
    } finally {
        // 如果没有成功加载数据，在这里设置loading为false
        if (!knowledgeGraphData.value.nodes || knowledgeGraphData.value.nodes.length === 0) {
            knowledgeGraphLoading.value = false
        }
    }
}

// 🔥 渲染详情页面的知识图谱
const renderDetailGraph = () => {
    if (!knowledgeGraphData.value.nodes || knowledgeGraphData.value.nodes.length === 0) {
        console.log('没有图谱数据可渲染')
        return
    }
    
    console.log('🎨 开始渲染详情页知识图谱...')
    
    // 🔥 增加多次尝试获取容器的机制
    const tryRender = (attempts = 0) => {
        const container = document.getElementById('detail-knowledge-graph')
        
        if (!container) {
            console.warn(`尝试 ${attempts + 1}: 找不到图谱容器，可能DOM还没完全渲染`)
            
            if (attempts < 5) {
                setTimeout(() => {
                    tryRender(attempts + 1)
                }, 200) // 每200ms重试一次，最多重试5次
                return
            } else {
                console.error('❌ 5次尝试后仍然找不到图谱容器，放弃渲染')
                ElMessage.error('知识图谱渲染失败：找不到容器元素')
                return
            }
        }
        
        console.log('✅ 找到图谱容器，开始渲染')
        
        // 清除旧的SVG
        d3.select('#detail-knowledge-graph').selectAll('*').remove()
        
        const width = container.clientWidth || 300
        const height = container.clientHeight || 250
        
        console.log('详情图谱容器尺寸:', { width, height })
        
        // 创建SVG
        detailSvg = d3.select('#detail-knowledge-graph')
            .append('svg')
            .attr('width', width)
            .attr('height', height)
            .style('border', '1px solid #eee')
            .style('border-radius', '8px')
        
        const g = detailSvg.append('g')
        
        // 准备数据
        const validNodes = knowledgeGraphData.value.nodes.filter(node => node && node.id && node.name)
        const validNodeIds = new Set(validNodes.map(node => node.id))
        
        const validLinks = knowledgeGraphData.value.links.filter(link => {
            const sourceId = typeof link.source === 'string' ? link.source : (link.source?.id || link.source)
            const targetId = typeof link.target === 'string' ? link.target : (link.target?.id || link.target)
            return sourceId && targetId && validNodeIds.has(sourceId) && validNodeIds.has(targetId)
        })
        
        console.log(`详情图谱: ${validNodes.length}个节点, ${validLinks.length}个连接`)
        
        // 🔥 如果没有有效数据，显示提示
        if (validNodes.length === 0) {
            g.append('text')
                .attr('x', width / 2)
                .attr('y', height / 2)
                .attr('text-anchor', 'middle')
                .style('fill', '#999')
                .style('font-size', '14px')
                .text('暂无图谱数据')
            return
        }
        
        // 处理连接数据
        const linksData = validLinks.map(link => ({
            source: typeof link.source === 'string' ? link.source : (link.source?.id || link.source),
            target: typeof link.target === 'string' ? link.target : (link.target?.id || link.target),
            type: link.type || '',
            label: link.label || ''
        }))
        
        // 应用预设位置（缩放到适合容器）
        const scaleX = width / 800  // 原图谱宽度800
        const scaleY = height / 600 // 原图谱高度600
        
        validNodes.forEach(node => {
            if (node.fx !== undefined && node.fy !== undefined) {
                node.x = node.fx * scaleX
                node.y = node.fy * scaleY
                node.fx = node.x
                node.fy = node.y
            } else {
                // 🔥 如果没有预设位置，设置默认位置
                node.x = width / 2 + (Math.random() - 0.5) * width * 0.6
                node.y = height / 2 + (Math.random() - 0.5) * height * 0.6
            }
        })
        
        // 绘制连线
        const link = g.append('g')
            .attr('class', 'links')
            .selectAll('line')
            .data(linksData)
            .enter().append('line')
            .attr('stroke', '#ccc')
            .attr('stroke-opacity', 0.8)
            .attr('stroke-width', 1.5)
            .attr('x1', d => {
                const sourceNode = validNodes.find(n => n.id === d.source)
                return sourceNode ? sourceNode.x : 0
            })
            .attr('y1', d => {
                const sourceNode = validNodes.find(n => n.id === d.source)
                return sourceNode ? sourceNode.y : 0
            })
            .attr('x2', d => {
                const targetNode = validNodes.find(n => n.id === d.target)
                return targetNode ? targetNode.x : 0
            })
            .attr('y2', d => {
                const targetNode = validNodes.find(n => n.id === d.target)
                return targetNode ? targetNode.y : 0
            })
        
        // 绘制节点
        const node = g.append('g')
            .attr('class', 'nodes')
            .selectAll('g')
            .data(validNodes)
            .enter().append('g')
            .attr('class', 'node')
            .attr('transform', d => `translate(${d.x || 0},${d.y || 0})`)
        
        // 添加节点圆圈
        node.append('circle')
            .attr('r', d => getDetailNodeRadius(d.level))
            .attr('fill', d => getDetailNodeColor(d.type, d.level, d.highlight))
            .attr('stroke', '#fff')
            .attr('stroke-width', 2)
            .style('cursor', 'pointer')
            .on('click', (event, d) => {
                console.log('点击详情图谱节点:', d)
                if (d.level > 2) { // 可以点击查看详情的节点
                    ElMessage.info(`查看${d.name}详情...`)
                }
            })
        
        // 添加节点标签
        node.append('text')
            .attr('dy', '0.35em')
            .attr('text-anchor', 'middle')
            .style('font-size', d => getDetailNodeFontSize(d.level))
            .style('font-weight', d => d.highlight ? 'bold' : 'normal')
            .style('fill', d => d.highlight ? '#000' : '#333') // 🔥 高亮节点用黑色文字，更清晰
            .style('pointer-events', 'none')
            .text(d => {
                const name = d.name || '未知'
                return name.length > 6 ? name.substring(0, 6) + '...' : name
            })
        
        console.log('✅ 详情页知识图谱渲染完成')
    }
    
    // 开始尝试渲染
    tryRender()
}

// 🔥 获取详情页节点半径
const getDetailNodeRadius = (level) => {
    const radiusMap = { 1: 20, 2: 16, 3: 12, 4: 10 }
    return radiusMap[level] || 12
}

// 🔥 获取详情页节点颜色
const getDetailNodeColor = (type, level, highlight) => {
    if (highlight) {
        // 🔥 高亮节点使用橙色背景，避免红配红
        return '#ff9500' // 橙色
    }
    
    if (level === 1) return '#1890ff' // 作物
    if (level === 2) return '#52c41a' // 类型
    
    const typeColorMap = {
        'variety': '#13c2c2',
        'disease': '#ff9c6e',
        'pest': '#fadb14',
        'stress': '#b37feb'
    }
    return typeColorMap[type] || '#8c8c8c'
}

// 🔥 获取详情页节点字体大小
const getDetailNodeFontSize = (level) => {
    const sizeMap = { 1: '12px', 2: '10px', 3: '9px', 4: '8px' }
    return sizeMap[level] || '9px'
}

// 🔥 跳转到完整知识图谱
const goToFullGraph = () => {
    router.push({
        name: 'CropGraph',
        query: {
            searchKeyword: pestDiseaseData.value.name
        }
    })
    ElMessage.success('正在跳转到完整知识图谱...')
}

// 🔥 创建测试图谱数据（用于调试）
const createTestGraphData = () => {
    console.log('📝 创建测试知识图谱数据')
    
    const currentName = pestDiseaseData.value.name || '小麦秆黑粉病'
    console.log('当前病虫害名称:', currentName)
    
    const testNodes = [
        {
            id: 'crop_1',
            name: '小麦',
            type: 'crop',
            level: 1,
            fx: 150,
            fy: 125,
            fixed: true
        },
        {
            id: 'type_disease_1',
            name: '小麦病害',
            type: 'disease_type',
            level: 2,
            fx: 75,
            fy: 75,
            fixed: true
        },
        {
            id: 'disease_1',
            name: currentName, // 🔥 确保使用当前病虫害名称
            type: 'disease',
            level: 3,
            fx: 25,
            fy: 50,
            fixed: true,
            highlight: true, // 🔥 高亮当前节点
            isSpecific: true
        },
        {
            id: 'disease_2',
            name: '小麦赤霉病',
            type: 'disease',
            level: 3,
            fx: 75,
            fy: 25,
            fixed: true
        },
        {
            id: 'disease_3',
            name: '小麦锈病',
            type: 'disease',
            level: 3,
            fx: 125,
            fy: 50,
            fixed: true
        }
    ]
    
    const testLinks = [
        { source: 'crop_1', target: 'type_disease_1', type: '包含' },
        { source: 'type_disease_1', target: 'disease_1', type: '包含' },
        { source: 'type_disease_1', target: 'disease_2', type: '包含' },
        { source: 'type_disease_1', target: 'disease_3', type: '包含' }
    ]
    
    knowledgeGraphData.value = {
        nodes: testNodes,
        links: testLinks
    }
    
    // 渲染测试图谱
    setTimeout(() => {
        renderDetailGraph()
    }, 100)
    
    ElMessage.success(`✨ "${currentName}" 已在知识图谱中高亮显示（橙色）`)
}

// 🔥 重试加载图谱
const retryLoadGraph = () => {
    console.log('🔄 重试加载知识图谱')
    knowledgeGraphData.value = { nodes: [], links: [] }
    loadKnowledgeGraph()
}

// 方法
const fetchDetail = async () => {
    try {
        loading.value = true
        const pestName = route.query.name

        console.log('🔍 开始获取病虫害详情，名称:', pestName)

        if (!pestName) {
            ElMessage.error('缺少病虫害名称参数')
            return
        }

        const response = await getPestDiseaseByName(pestName)
        console.log('📡 API响应:', response)

        if (response.code === 200 && response.data) {
            pestDiseaseData.value = response.data
            console.log('✅ 获取病虫害详情成功:', pestDiseaseData.value)

            // 重置图片索引
            currentImageIndex.value = 0

            // 更新页面标题
            document.title = `${pestDiseaseData.value.name} - 病虫害详情`
            
            // 🔥 加载知识图谱
            loadKnowledgeGraph()
            
            // 🔥 临时测试：如果API没有响应，创建测试数据
            setTimeout(() => {
                if (!knowledgeGraphData.value.nodes || knowledgeGraphData.value.nodes.length === 0) {
                    console.log('🧪 使用测试数据渲染图谱')
                    createTestGraphData()
                }
            }, 2000)
        } else {
            console.error('❌ API返回错误:', response)
            ElMessage.error(response.msg || '获取病虫害详情失败')
        }
    } catch (error) {
        console.error('💥 获取病虫害详情出错:', error)
        ElMessage.error('获取病虫害详情失败，请检查网络连接')
    } finally {
        loading.value = false
    }
}

const goBack = () => {
    router.go(-1) // 返回上一页
}

const formatDate = (dateString) => {
    if (!dateString) return '-'
    return new Date(dateString).toLocaleString('zh-CN')
}

const switchMainImage = (index) => {
    currentImageIndex.value = index
    console.log('切换主图到索引:', index)
}

const printDetail = () => {
    window.print()
}

const exportDetail = () => {
    ElMessage.info('导出功能开发中...')
    // 这里可以实现导出为PDF或Word的功能
}

// 生命周期
onMounted(() => {
    console.log('🚀 详情页面加载，路由参数:', route.query)
    fetchDetail()
})

// 监听图片列表变化，重置索引
watch(imageList, (newList) => {
    if (newList.length > 0 && currentImageIndex.value >= newList.length) {
        currentImageIndex.value = 0
    }
})
</script>

<style scoped>
.detail-container {
    padding: 20px;
    max-width: 1400px;
    margin: 0 auto;
    min-height: calc(100vh - 120px);
}

.detail-header {
    margin-bottom: 20px;
}

.header-content {
    margin-top: 16px;
}

.title-section {
    display: flex;
    align-items: center;
    gap: 16px;
}

.title-section h1 {
    margin: 0;
    color: #303133;
    font-size: 28px;
    font-weight: 600;
}

.loading-container {
    padding: 40px;
}

.detail-content {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

/* 等高容器 - 改进版 */
.equal-height-container {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    align-items: start;
    min-height: 600px;
}

/* 左侧列 */
.left-column {
    display: flex;
    flex-direction: column;
    gap: 20px;
    min-height: 600px;
}

/* 右侧列 */
.right-column {
    display: grid;
    grid-template-rows: 1fr 1fr;
    gap: 20px;
    height: 600px;
    max-height: 800px;
    min-height: 600px;
}

/* 当左侧内容较多时，右侧自适应 */
.left-column:has(.info-card:nth-child(4))~.right-column,
.left-column:has(.info-card:nth-child(5))~.right-column {
    height: auto;
    min-height: 600px;
}

/* 使用CSS容器查询的替代方案 */
@supports not selector(:has(*)) {
    .right-column {
        height: clamp(600px, 50vh, 800px);
    }
}

/* 右侧每个区域 */
.right-section {
    display: flex;
    flex-direction: column;
    min-height: 0;
    height: 100%;
}

/* 占满高度的卡片 */
.full-height-card {
    display: flex;
    flex-direction: column;
    height: 100%;
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s ease;
    min-height: 0;
}

.full-height-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

/* 卡片内容区域 */
.card-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 20px;
    overflow: hidden;
    min-height: 0;
}

/* 通用卡片样式 */
.info-card {
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s ease;
    height: fit-content;
}

.info-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.card-header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    color: #303133;
}

.card-icon {
    font-size: 18px;
}

.symptoms-icon {
    color: #e6a23c;
}

.conditions-icon {
    color: #67c23a;
}

.methods-icon {
    color: #409eff;
}

.graph-icon {
    color: #8b5cf6;
}

.content-text {
    line-height: 1.8;
    color: #606266;
    font-size: 14px;
    text-align: justify;
    white-space: pre-wrap;
    word-break: break-all;
}

/* 图片展示区域 */
.image-gallery {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

/* 单张图片布局 */
.single-image-container {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 0;
}

.single-image {
    width: 100%;
    height: 100%;
    max-height: 100%;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.single-image:hover {
    transform: scale(1.02);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 多张图片布局 */
.multiple-images-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 12px;
    min-height: 0;
}

.main-image-container {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 0;
}

.main-image {
    width: 100%;
    height: 100%;
    max-height: 100%;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.main-image:hover {
    transform: scale(1.02);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 缩略图容器 */
.thumbnail-container {
    display: flex;
    gap: 8px;
    overflow-x: auto;
    padding: 4px 0;
    max-height: 80px;
}

.thumbnail-item {
    flex-shrink: 0;
    width: 60px;
    height: 60px;
    border-radius: 6px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s ease;
    border: 2px solid transparent;
}

.thumbnail-item:hover {
    transform: scale(1.05);
    border-color: #409eff;
}

.thumbnail-item.active {
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.thumbnail-image {
    width: 100%;
    height: 100%;
}

/* 错误状态样式 */
.image-error-large {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 14px;
    gap: 8px;
}

.thumbnail-error {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
}

/* 🔥 知识图谱样式 */
.knowledge-graph-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
}

.detail-graph-display {
    width: 100%;
    height: 250px;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    background: #fafafa;
    position: relative;
    overflow: hidden;
}

.graph-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200px;
    color: #909399;
    gap: 12px;
}

.graph-loading p {
    margin: 0;
    font-size: 14px;
}

.knowledge-graph-placeholder {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    background: #fafafa;
    min-height: 250px;
}

/* 🔥 详情页D3图谱节点样式 */
.detail-graph-display :deep(.nodes circle) {
    cursor: pointer;
    transition: all 0.3s ease;
}

.detail-graph-display :deep(.nodes circle:hover) {
    stroke-width: 3px;
    filter: brightness(1.1);
}

.detail-graph-display :deep(.nodes text) {
    pointer-events: none;
    font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
    user-select: none;
}

.detail-graph-display :deep(.links line) {
    stroke: #ccc;
    stroke-opacity: 0.8;
}

/* 无内容状态 */
.no-content {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
}

/* 操作按钮 */
.action-bar {
    position: fixed;
    bottom: 20px;
    right: 20px;
    display: flex;
    gap: 12px;
    background: white;
    padding: 12px 16px;
    border-radius: 24px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    z-index: 100;
}

/* 响应式设计 */
@media (max-width: 1200px) {
    .equal-height-container {
        grid-template-columns: 1fr;
        gap: 20px;
    }

    .right-column {
        grid-template-rows: auto auto;
        height: auto;
    }
}

@media (max-width: 768px) {
    .detail-container {
        padding: 16px;
    }

    .title-section {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }

    .title-section h1 {
        font-size: 24px;
    }

    .knowledge-graph-placeholder {
        min-height: 200px;
    }

    /* 移动端图片优化 */
    .thumbnail-container {
        max-height: 60px;
    }

    .thumbnail-item {
        width: 50px;
        height: 50px;
    }

    .multiple-images-container {
        gap: 8px;
    }

    .action-bar {
        position: static;
        margin-top: 20px;
        justify-content: center;
        box-shadow: none;
        background: transparent;
    }
    
    .detail-graph-display {
        height: 200px;
    }
}

/* 打印样式 */
@media print {

    .detail-header .el-breadcrumb,
    .action-bar {
        display: none;
    }

    .detail-container {
        padding: 0;
        max-width: none;
    }

    .info-card,
    .full-height-card {
        break-inside: avoid;
        box-shadow: none;
        border: 1px solid #ddd;
    }

    .content-text {
        color: #000;
    }

    .knowledge-graph-placeholder {
        border: 1px solid #000;
    }
}
</style>